<template>
    <MenuPage 
      ref="selectTable"
      :data="targetList" 
      :columns="targetCol"
      :page.sync="query.pageIndex"
      :size.sync="query.pageSize"
      :total="totalCount"
      :loading="tableLoading"
      showSelectTag
      :selection.sync="selectTargets" 
      @queryFun="queryTargetList">
      <template slot="search">
          <Button
            ghost
            style="height: 32px;margin-right: 15px"
            type="primary"
            icon="ios-cloud-upload-outline"
            v-if="distributed"
            @click="reportedTargets"
            >漏洞靶标上报</Button
          >
          <Button type="primary" ghost class="md-add-jh" @click="getTargetInfo('')"
            >创建漏洞靶标</Button
          >
          <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
          <div style="height: 32px;line-height: 32px;margin-left: 15px;flex-shrink: 0;">
            <Checkbox v-model="creatByMeModal" @on-change="debounceSearch">由我创建</Checkbox>
          </div>
          <Select filterable
            @on-change="changePage(1)"
            v-model="queryTargetInfo.rangeId"
            style="width:155px"
            :placeholder="'靶场:' + mainRange"
            clearable
            v-if="distributedRange"
          >
            <Option
              v-for="(items, index) in rangeAllList"
              :value="items.id"
              :key="index + 'range'"
              >{{ items.name }}</Option
            >
          </Select>
          <Select filterable
            v-model="queryTargetInfo.docFlag"
            style="width:150px;margin-left: 15px"
            clearable
            placeholder="是否有漏洞说明文档"
            @on-change="changePage(1)"
          >
            <Option value="true">是</Option>
            <Option value="false">否</Option>
          </Select>
          <Select filterable
            clearable
            placeholder="危险等级"
            v-model="queryTargetInfo.leakLevel"
            @on-change="changePage(1)"
            style="width:150px;margin-left: 15px"
          >
            <Option value="low" label="低危"> </Option>
            <Option value="middle" label="中危"> </Option>
            <Option value="high" label="高危"> </Option>
          </Select>
          <Select filterable
            clearable
            placeholder="可见范围"
            style="width: 150px;margin-left: 15px "
            v-model="queryTargetInfo.visibility"
            @on-change="changePage(1)"
          >
            <Option value="public">系统</Option>
            <Option value="share">单位</Option>
            <Option value="private">个人</Option>
          </Select>
          <Input
            clearable
            v-model.trim="queryTargetInfo.name"
            placeholder="漏洞靶标名称"
            @on-change="debounceSearch"
            style="width:180px;margin-left: 15px"
          ></Input>
          <Input
            clearable
            v-model.trim="queryTargetInfo.imageName"
            placeholder="镜像名称"
            @on-change="debounceSearch"
            style="width:180px;margin-left: 15px"
          ></Input>
          <Input
            clearable
            v-model.trim="queryTargetInfo.cve"
            placeholder="CVE编号"
            @on-change="debounceSearch"
            style="width:180px;margin-left: 15px"
          ></Input>
          <Input
            clearable
            v-model.trim="queryTargetInfo.leakType"
            placeholder="漏洞名称"
            @on-change="debounceSearch"
            style="width:180px;margin-left: 15px"
          ></Input>

          <Button
            class="header-btn"
            type="primary"
            ghost
            style="height: 32px;margin-left: 5px;"
            @click="refreshIcon()"
            ><i class="el-icon-refresh-right"
          /></Button>
      </template>
    <Modal v-model="detailModal" title="靶标详情" :mask-closable="false" :width="800" footer-hide>
      <!-- <div>
		        {{detailText}}
	        </div> -->
      <div id="quesDetail">
        <p>
          <span class="label">漏洞靶标名称</span><span>{{ detailText.name }}</span>
        </p>
        <p>
          <span class="label">创建者</span><span>{{ detailText.creatorName }}</span>
        </p>
        <p>
          <span class="label">镜像</span><span>{{ detailText.imageName }}</span>
        </p>
        <p>
          <span class="label">可见范围</span
          ><span :style="{ color: setVisibility(detailText.visibility).color }">{{
            setVisibility(detailText.visibility).text
          }}</span>
        </p>
        <p>
          <span class="label">CVE编号</span><span>{{ detailText.cve }}</span>
        </p>
        <p>
          <span class="label">开放端口</span><span>{{ detailText.openPort }}</span>
        </p>
        <!--<p v-if="detailText.isNeedEnv == 1"><span class='label'>镜像</span><span>{{detailText.imageName}}</span></p>
		        <p v-if="detailText.isNeedEnv == 1"><span class='label'>配额</span><span>{{detailText.flavorName}}</span></p>
		        <p v-if="detailText.isNeedEnv == 1"><span class='label'>端口</span><span>{{detailText.port}}</span></p> -->
        <p>
          <span class="label">漏洞名称</span><span>{{ detailText.leakType }}</span>
        </p>
        <p>
          <span class="label">漏洞等级</span><span>{{ filterLevel(detailText.leakLevel) }}</span>
        </p>
        <!--<p v-if="detailText.isFixedFileFlag == 1"><span class='label'>Flag路径</span><span>{{detailText.flagPath}}</span></p>
		        <p v-if="detailText.isFixedFileFlag == 0"><span class='label'>Flag</span><span>{{detailText.flag}}</span></p>
		        <p v-if="detailText.isFixedFileFlag == 0"><span class='label'>Flag匹配类型</span><span>{{detailText.flagMatchType == 0 ? '严格匹配' : '模糊匹配'}}</span></p> -->
        <p>
          <span class="label">漏洞描述</span><span>{{ detailText.description }}</span>
        </p>
        <p>
          <span class="label">漏洞说明文档</span
          ><span
            ><a :href="'/api/minio/download?path=' + detailText.docPath" download="">{{
              detailText.docName
            }}</a></span
          >
        </p>
        <p>
          <span class="label">脚本Id</span><span>{{ detailText.scriptId }}</span>
        </p>
        <!--<p><span class='label'>描述</span><span>{{detailText.description}}</span></p>-->
      </div>
    </Modal>
    <Modal
      v-model="targetModal.show"
      :title="targetModal.title"
      @on-ok="saveTarget"
      @on-cancel="cancel('formValidate')"
      :loading="targetModal.loading"
      :mask-closable="false"
      width="550"
    >
      <Form
        :label-width="100"
        :model="formValidate"
        :rules="ruleValidate"
        ref="formValidate"
        style="width: 500px"
      >
        <FormItem label="漏洞靶标名称" prop="name">
          <Input
            v-model.trim="formValidate.name"
            placeholder="漏洞靶标名称长度为1-64个字符"
          ></Input>
        </FormItem>
        <FormItem label="可见范围" prop="visibility">
          <RadioGroup v-model="formValidate.visibility" @on-change="changePublic">
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
          <Tooltip
            v-if="formValidate.id"
            style="margin-left: 10px;"
            :transfer="true"
            max-width="200"
            content="可见范围由个人修改为单位时，靶标使用的个人资源(如:镜像)的可见范围将变为单位"
            placement="top"
          >
            <Icon type="ios-alert" class="ios-alert" />
          </Tooltip>
          <!-- <span v-if="formValidate.id" style="color:#f90;display: inline-block;">
					
					<Icon type="ios-information-circle-outline" />可见范围由个人修改为单位时，靶标使用的个人资源(如:镜像)的可见范围将变为单位</span> -->
        </FormItem>

        <!-- docker -->
        <FormItem label="镜像来源">
          <RadioGroup v-model="FormValidate.ImageSource" @on-change="setImageSource">
            <Radio label="1">选择已有镜像</Radio>
            <Radio label="2">上传Docker</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="选择运行环境"
          prop="dockerContent.tempId"
          v-if="FormValidate.ImageSource === '2'"
        >
          <Select filterable v-model="formValidate.dockerContent.tempId" filterable label-in-value>
            <Option
              v-for="item in dockerList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              :title="item.name"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem
          label="Docker文件"
          prop="dockerContent.dockerName"
          v-if="FormValidate.ImageSource === '2'"
        >
          <section>
            <Row>
              <Upload
                ref="uploadDocker"
                :action="uploadDockerUrl"
                :show-upload-list="false"
                :on-success="getDockerUrl"
                :on-progress="getProgress"
                :before-upload="handleBeforeUploadDocker"
                :headers="uploadHeader"
                style="display:inline-block;"
              >
                <Button icon="ios-cloud-upload-outline" :disabled="uploadDockerList.length > 0"
                  >上传Docker文件</Button
                >
              </Upload>
              <!-- <span style="color:#ff9900"> <Icon type="ios-information-circle-outline" />请上传doc,docx,pdf等格式文件,文件大小不能超过20M</span> -->

              <!--{{filename}}-->
            </Row>
            <div class="demo-upload-list" v-for="item in uploadDockerList">
              <template v-if="item.status === 'finished'"> </template>
              <template v-else>
                <span style="margin-right:5px;">文件名：{{ item.name }}</span>
                <span style="margin-right:5px;">文件大小：{{ getFileSize(item.size) }}</span>
                <span style="margin-right:5px;">上传速度：{{ speed }}</span>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <div class="chose-wrap" v-show="dockerFilename">
              <div style="display: flex;justify-content: flex-start;align-items: center">
                <img src="../../assets/exper/guide.png" class="chose-s2-icon" />
                <div class="chose-name">{{ dockerFilename }}</div>
              </div>
              <img
                src="../../assets/globalIcon/dis-del.png"
                style="width: 13px;height: 14px;cursor: pointer"
                @click="clearDocker"
              />
            </div>
            <!-- <p v-if="showTip" style="color:red;">请上传doc,pdf格式文件,文件大小不能超过20M</p> -->
            <!-- <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传文件</div> -->
          </section>
        </FormItem>
        <FormItem
          label="flag路径"
          prop="dockerContent.flagPath"
          v-if="FormValidate.ImageSource === '2'"
        >
          <Input v-model.trim="formValidate.dockerContent.flagPath"></Input>
        </FormItem>
        <FormItem
          label="docker运行命令及参数"
          prop="dockerContent.cmd"
          v-if="FormValidate.ImageSource === '2'"
        >
          <Input v-model.trim="formValidate.dockerContent.cmd"></Input>
          <Tooltip
            class="ios-alert1"
            style="margin-left: 10px;"
            :transfer="true"
            max-width="400"
            placement="top"
          >
            <Icon type="ios-alert" />
            <div slot="content">
              <p>docker 镜像名称用 %s 代替，如：</p>
              <!-- <p>docker run -d --name=server-db -p 3306:3306 <i style="color:#fd5f5f">centos6.8-mysql</i> /usr/bin/mysql_safe –d</p> -->
              <p>
                docker run -d --name=server-db -p 3306:3306
                <i style="color:#fd5f5f">%s</i> /usr/bin/mysql_safe –d
              </p>
            </div>
          </Tooltip>
        </FormItem>

        <FormItem
          label="选择已有镜像"
          prop="imageId"
          class="SelForm"
          v-if="FormValidate.ImageSource === '1'"
        >
          <Select filterable v-model="formValidate.imageId" filterable label-in-value @on-change="changeImage">
            <Option
              v-for="item in imageList"
              :key="item.id"
              :value="item.id"
              :label="item.imageName"
              :title="item.imageName"
              :disabled="
                (formValidate.visibility == 'share' || !isOwn) && item.localVisibility == 'private'
              "
            >
            </Option>
          </Select>
          <Button
            type="text"
            size="small"
            @click="addImage"
            class="AddImageBtn md-add-jh"
          ></Button>
        </FormItem>
        <FormItem label="漏洞名称" prop="leakType">
          <Input v-model.trim="formValidate.leakType"></Input>
        </FormItem>
        <FormItem label="漏洞等级" prop="leakLevel">
          <Select filterable v-model="formValidate.leakLevel">
            <Option value="low" label="低危"> </Option>
            <Option value="middle" label="中危"> </Option>
            <Option value="high" label="高危"> </Option>
          </Select>
        </FormItem>
        <FormItem label="CVE编号" prop="cve">
          <Input v-model.trim="formValidate.cve" placeholder="请输入CVE编号..."></Input>
        </FormItem>
        <FormItem label="开放端口" prop="openPort">
          <Input v-model.trim="formValidate.openPort"></Input>
        </FormItem>
        <FormItem label="漏洞描述" prop="description">
          <Input
            v-model.trim="formValidate.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述信息"
          ></Input>
        </FormItem>
        <FormItem label="漏洞说明文档" prop="writeUpPath">
          <section>
            <Row>
              <Upload
                ref="upload"
                :action="uploadAction"
                :show-upload-list="false"
                :format="['doc', 'docx', 'pdf']"
                :on-format-error="handleFormatError"
                :on-success="getImageUrl"
                :on-progress="getProgress"
                :before-upload="handleBeforeUpload"
                :headers="uploadHeader"
                style="display:inline-block;"
              >
                <Button icon="ios-cloud-upload-outline" :disabled="uploadList.length > 0"
                  >上传漏洞说明文档</Button
                >
              </Upload>
              <!-- <span style="color:#ff9900"> <Icon type="ios-information-circle-outline" />请上传doc,docx,pdf等格式文件,文件大小不能超过20M</span> -->
              <Tooltip
                style="margin-left: 10px;"
                :transfer="true"
                max-width="200"
                content="请上传doc,docx,pdf等格式文件"
                placement="top"
              >
                <Icon type="ios-alert" class="ios-alert" />
              </Tooltip>
              <!-- 文件大小不能超过20M -->
              <!--{{filename}}-->
            </Row>
            <div class="demo-upload-list" v-for="item in uploadList">
              <template v-if="item.status === 'finished'"> </template>
              <template v-else>
                <span style="margin-right:5px;">文件名：{{ item.name }}</span>
                <span style="margin-right:5px;">文件大小：{{ getFileSize(item.size) }}</span>
                <span style="margin-right:5px;">上传速度：{{ speed }}</span>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <div class="chose-wrap" v-show="filename">
              <div style="display: flex;justify-content: flex-start;align-items: center">
                <img src="../../assets/exper/guide.png" class="chose-s2-icon" />
                <div class="chose-name">{{ filename }}</div>
              </div>
              <img
                src="../../assets/globalIcon/dis-del.png"
                style="width: 13px;height: 14px;cursor: pointer"
                @click="clearDoc"
              />
            </div>
            <p v-if="showTip" style="color:red;">请上传doc,pdf格式文件</p>
            <!-- ,文件大小不能超过20M -->
            <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传文件</div>
          </section>
        </FormItem>
      </Form>
    </Modal>

    <!-- 脚本操作 -->
    <Checker
      ref="check"
      @queryTargetList="queryTargetList"
      @getAllImage="getAllImage"
      @changeImage="changeImage"
    ></Checker>
  </MenuPage>
</template>
<script>
import { getallImage, delfile } from '@/api/question';
import { createTarget, delTarget, queryTargetList, updateTarget } from '@/api/drill';
import { getAllDocker, getOperateInfo } from '@/api/target.js';
import encryption from '@/libs/encryption.js';
import { validateName } from '@/libs/reg';
import { debounce } from '@/libs/utils';
import Checker from '@/components/checker/Checker';
import { reportedTargets, getRangeAll } from '@/api/reported-data';
import resourcesReportedMixin from '@/mixin/resources-reported-mixin';
import pageTitle from '@/mixin/pageTitle';
export default {
  name: 'target',
  components: { Checker },
  props: ['show'],
  mixins: [resourcesReportedMixin,pageTitle],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    const portValidator = (rule, value, callback) => {
      if (value) {
        let reg = /^[0-9]*$/;
        if (!(parseInt(value) > 0 && parseInt(value) <= 65535)) {
          callback(new Error('请输入1-65535之间的数字'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      mainRangeflag: true,
      mainRange: '',
      rangeAllList: [],
      distributed: September.distributed,
      selectTargets: [],
      selectAllQuestion: false,
      columns1: [
        {
          title: 'Name',
          key: 'name'
        },
        {
          title: 'Age',
          key: 'age'
        },
        {
          title: 'Address',
          key: 'address'
        }
      ],
      data1: [
        {
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        },
        {
          name: 'Joe Black',
          age: 30,
          address: 'Sydney No. 1 Lake Park',
          date: '2016-10-02'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        }
      ],
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      query: {
        pageIndex: 1,
        pageSize: 10
      },
      queryTargetInfo: {},
      targetList: [],
      tableLoading:false,
      totalCount: 0,
      flavorList: [],
      detailModal: false,
      detailText: '',
      targetModal: {
        show: false,
        loading: true,
        add: true,
        title: '创建漏洞靶标'
      },
      formValidate: {
        creator: September.userId,
        cve: '', //CVE编号
        description: '', //漏洞描述
        imageId: '',
        imageName: '', //镜像名称
        visibility: 'share', //可见范围
        leakType: '', //漏洞名称
        leakLevel: '', //漏洞等级
        openPort: '', //开放端口
        name: '', //名称
        targetlibrary: '', //靶标知识库
        docName: '', //说明文档
        docPath: '', //说明文档
        explainFileRecordId: '', //说明文档
        dockerContent: { tempId: '', dockerName: '', dockerPath: '', flagPath: '', cmd: '' }
      },
      FormValidate: {
        ImageSource: '1' //镜像来源 '1'为选择已有镜像，'2'为上传docker
      },
      ruleValidate: {
        name: [
          {
            required: true,
            max: 64,
            message: '名称长度为1—64个字符',
            trigger: 'change'
          },
          { validator: validateName, trigger: 'change' }
        ],
        leakType: [
          {
            required: true,
            message: '漏洞名称不能为空',
            trigger: 'change'
          }
        ],
        leakLevel: [
          {
            required: true,
            message: '漏洞等级不能为空',
            trigger: 'change'
          }
        ],
        imageName: [
          {
            required: true,
            message: '镜像不能为空',
            trigger: 'change'
          }
        ],
        imageId: [
          {
            required: true,
            message: '镜像不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.tempId': [
          {
            required: true,
            message: '运行环境不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.dockerName': [
          {
            required: true,
            message: 'docker文件不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.flagPath': [
          {
            required: true,
            message: 'flag路径不能为空',
            trigger: 'change'
          }
        ],
        'dockerContent.cmd': [
          {
            required: true,
            message: 'docker运行命令及参数不能为空',
            trigger: 'change'
          }
        ],
        visibility: [
          {
            required: true,
            message: '可见范围不能为空',
            trigger: 'change'
          }
        ],
        openPort: [
          {
            validator: portValidator,
            trigger: 'change'
          }
        ]
      },
      targetCol: [
        {
            type: 'selection',
            width: 60,
            align: 'left',
            show:() => {
              return this.distributed
            }
        },
        {
            type: 'link',
            title: '名称',
            key: 'name',
            tooltip: true,
            on:{
              click: (data) => {
                this.detailModal = true;
                this.detailText = data;
              }
            }
        },
        {
            title: '镜像',
            key: 'imageName',
            minWidth:100,
            tooltip: true
        },
        {
            title: '状态',
            key: 'statusCHName',
            width: 100,
            setColor: (statusCHName, data) => {
                return this.setColor(data.status);
            },
            disabled:(item)=>{
              return item.status == 'active'
            },
            tootip:true,
            tooltipKey:'note'
        },
        {
            title: '验证状态',
            key: 'statusName',
            width: 100,
            render: (h, params) => {
                return h(
                    'Tooltip',
                    {
                        class: 'ivu-table-cell-tooltip',
                        props: {
                            disabled: params.row.verify !== 'error',
                            content: params.row.msg,
                            transfer: true
                        },
                        style: {
                            color: this.setScriptColor(params.row.verify)
                        },
                        on: {
                            'on-popper-show': () => {
                                this.mouseOver(params.row);
                            }
                        }
                    },
                    [
                        h(
                            'span',
                            { class: 'ivu-table-cell-tooltip-content' },
                            params.row.statusName
                        )
                    ]
                );
            }
        },
        {
          title:'上报状态',
          key:'reportedStatus',
          show:() => {
            return this.distributed
          },
          filter:(reportedStatus) => {
            return ['0', '1'].includes(reportedStatus)
              ? '上报失败'
              : reportedStatus === '2'
              ? '上报成功'
              : '未上报'
          },
          setColor:(reportedStatus) => {
            return ['0', '1'].includes(reportedStatus)
              ? '#ed4014'
              : reportedStatus === '2'
              ? '#19be6b'
              : 'grey'
          },
          disabled:(data) => {
            return !['0', '1'].includes(data.reportedStatus)
          },
          tooltip:true,
          tooltipKey:'reportedMsg'
        },
        {
            title: 'CVE编号',
            key: 'cve',
            tooltip: true
        },
        {
            title: '开放端口',
            key: 'openPort',
            tooltip: true
        },
        {
            title: '漏洞名称',
            key: 'leakType',
            tooltip: true
        },
        {
            title: '漏洞等级',
            key: 'leakLevel',
            width: 100,
            filter: this.filterLevel
        },
        // {
        //     title: '是否存在漏洞说明文档',
        //     key: 'docPath',
        //     filter: (docPath) => {
        //         return docPath ? '是' : '否';
        //     }
        // },
        {
            title: '漏洞说明文档',
            key: 'docName',
            type:'link',
            tooltip: true,
            setPath: (data) => {
                return `/api/minio/download?path=${data.docPath}`;
            }
        },
        {
            title: '漏洞描述',
            key: 'description',
            tooltip: true
        },
        {
            title: '可见范围',
            key: 'visibility',
            minWidth:100,
            filter: (visible, data) => {
                return this.setVisibility(visible).text
                // return this.filterVisible(visible, 'text');
            },
            setColor: (visible, data) => {
                return this.setVisibility(visible).color
                // return this.filterVisible(visible, 'color');
            }
        },
        {
            title: '创建者',
            key: 'creatorName',
            tooltip: true
        },
        {
            title: '操作',
            width: 160,
            slot: 'action',
            fixed:'right',
            opList: [
                {
                    txt: '脚本',
                    on:{
                      click:(data,e) => {
                        this.openCheck(data)
                      }
                    },
                    setColor: (data) => {
                        return data.scriptId ? '#3f69b3' : '#e38100';
                    }
                },
                {
                    txt: '修改',
                    on:{
                      click:(data,e) => {
                        this.getTargetInfo(data)
                      }
                    },
                    disabled: this.setIsClick
                },
                {
                    txt: '删除',
                    tooltip: true,
                    type: 'delete',
                    title: '确定要删除这个靶标？',
                    on:{
                      click:(data,e) => {
                        this.delTarget(data)
                      }
                    },
                    disabled: this.setIsClick
                }
            ]
        }
    ],
    imageList: [],
      dockerList: [],
      uploadAction: '/api/minio/upload/permanent?visibility=company&type=docs&bucket=docs',
      uploadDockerUrl: '/api/minio/upload?bucket=docker-image-file',
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      uploadList: [],
      uploadDockerList: [],
      uploaderror: false,
      speed: 0,
      filename: '',
      dockerFilename: '',
      showTip: false,
      // 显示
      showDataList: true,
      showDefImg: false,
      creatByMeModal: false,
      delDocIds: [],
      proSetInterval: '',
      saveTargetStatusArr: []
    };
  },
  computed: {
    isOwn: function() {
      return this.USER_ID == this.formValidate.creator || !this.formValidate.creator;
    },
    distributedRange() {
      return this.$store.state.user.distributedRange;
    }
  },
  filters: {
    // filterLevel(level){
    //   if(level == '1'){
    //     return '低危'
    //   }else if(level == '2'){
    //     return '中危'
    //   }else if(level == '3'){
    //     return '高危'
    //   }
    // }
  },
  methods: {
    //查询所有分靶场信息
    queryAllRange() {
      getRangeAll().then((res) => {
        if (res.code === 1) {
          let mainRange = res.data.items.find((item) => {
            return item.level== 'LOCAL';
          });
          this.mainRange = mainRange.name || '选择靶场';
          this.rangeAllList = res.data.items;
        }
      });
    },
    setMainOrBranch() {
      let res = this.rangeAllList.find((item) => {
        return item.id == this.queryTargetInfo.rangeId;
      });
      if (res && res.level != 'LOCAL') {
        this.mainRangeflag = false; // 分靶场
      } else {
        this.mainRangeflag = true; // 主靶场
      }
    },
    // 上报漏洞靶标
    reportedTargets() {
      if (this.selectTargets.length == 0) {
        this.$Message.warning('请选择漏洞靶标');
        return;
      }
      reportedTargets(this.selectTargets.map((item) => item.id))
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.$Message.info('上报漏洞靶标成功');
          this.queryTargetList();
          this.selectTargets = [];
          this.selectAllQuestion = false;
          this.targetList.forEach((item) => this.$set(item, '_checked', false));
        })
        .catch(() => {
          this.$Message.error('上报漏洞靶标异常');
        });
    },
    //选择导出用户
    handleCheckAllQuestion(e) {
      this.selectAllQuestion = e;
      this.targetList.forEach((question) => {
        this.checkSingleQuestion(e, question);
      });
    },
    checkSingleQuestion(e, question) {
      if (e && !this.selectTargets.map((question) => question.id).includes(question.id)) {
        this.selectTargets.push(question);
      } else if (!e && this.selectTargets.map((question) => question.id).includes(question.id)) {
        let index = this.selectTargets.findIndex((item) => question.id == item.id);
        this.selectTargets.splice(index, 1);
      }
      let checkudQuestion = this.targetList.find((item) => item.id == question.id);
      if (checkudQuestion) {
        this.$set(checkudQuestion, '_checked', e);
      }
      if (
        this.targetList.length > 0 &&
        this.targetList.every((question) => question._checked === true)
      ) {
        this.selectAllQuestion = true;
      } else {
        this.selectAllQuestion = false;
      }
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      // this.query.pageSize = Math.floor(this.setTableHei / 96);
    },
    queryTargetList(isRefresh) {
      if (!isRefresh) {
        // 非刷新操作才需要展示等待中的画面
        this.tableLoading = true
        this.showDataList = false;
        this.showDefImg = true;
      }
      clearTimeout(this.proSetInterval);
      this.saveTargetStatusArr = [];
      if (this.creatByMeModal) {
        this.queryTargetInfo.creator = this.USER_ID;
        this.queryTargetInfo.self = true;
      }
      queryTargetList(this.queryTargetInfo, this.query).then(async (data) => {
        if (data.code == 1) {
          let items = data.data.items;

          let questionIds = this.selectTargets.map((question) => question.id);
          let checkedNum = 0;
          items.forEach((question) => {
            if (questionIds.includes(question.id)) {
              this.$set(question, '_checked', true);
              checkedNum++;
            } else {
              this.$set(question, '_checked', false);
            }
          });
          if (checkedNum && items.length === checkedNum) {
            this.selectAllQuestion = true;
          } else {
            this.selectAllQuestion = false;
          }

          this.totalCount = +data.data.total;
          this.queryTargetInfo.creator = '';
          this.queryTargetInfo.self = false;
          await this.getReportedStatus_mixins(items).then();
          items.forEach((item) => {
            item.status == 'saving'
              ? this.$set(item, 'statusCHName', '创建中')
              : item.status == 'create_ing'
              ? this.$set(item, 'statusCHName', '镜像生成中')
              : item.status == 'error'
              ? this.$set(item, 'statusCHName', '创建失败')
              : this.$set(item, 'statusCHName', '创建成功');
            item.verify == 'none'
              ? this.$set(item, 'statusName', '未验证')
              : item.verify == 'active'
              ? this.$set(item, 'statusName', '验证成功')
              : item.verify == 'error'
              ? this.$set(item, 'statusName', '验证失败')
              : this.$set(item, 'statusName', '验证中');
            if (
              item.status == 'saving' ||
              item.status == 'create_ing' ||
              item.verify == 'verify_ing'
            ) {
              this.saveTargetStatusArr.push(item);
            }
          });
          if (this.saveTargetStatusArr.length > 0) {
            this.proSetInterval = setTimeout(() => {
              this.queryTargetList(true);
            }, 3000);
          } else {
            clearTimeout(this.proSetInterval);
          }
          this.targetList = items;
          if (items.length > 0) {
            this.showDataList = true;
            this.showDefImg = false;
          } else {
            this.showDataList = false;
            this.showDefImg = true;
          }
          this.setMainOrBranch();
        } else {
          this.$Message.warning(data.message);
          this.showDataList = false;
          this.showDefImg = true;
        }
        this.tableLoading = false
      }).catch(error => {
        this.tableLoading = false
      });
    },
    delTarget(item) {
      delTarget(item.id).then((data) => {
        if (data.code == 1) {
          this.$Message.info({
            content: '删除靶机成功',
            duration: 3
          });
          this.distributed && this.$refs.selectTable.closeItem(item)
          if (this.query.pageIndex > 1 && this.targetList.length === 1) {
            this.query.pageIndex -= 1;
          }
          this.queryTargetList();
          //删除说明文档
          if (item.explainFileRecordId) {
            this.delDocIds = [item.explainFileRecordId];
            this.delFiles();
          }
        } else {
          this.$Message.warning(data.message);
        }
      });
    },
    //			modifyTarget() {
    //				modifyTarget(this.formValidate).then(data => {
    //					this.cancelLoading('targetModal');
    //					if(data.code == 1) {
    //						this.$Message.info(data.message);
    //						this.targetModal.show = false;
    //						this.queryTargetList();
    //					} else {
    //						this.$Message.warning(data.message);
    //					}
    //				})
    //			},
    createTarget() {
      if (this.FormValidate.ImageSource == '1') {
        this.formValidate.dockerContent = '';
      } else if (this.FormValidate.ImageSource == '2') {
        this.formValidate.imageId = '';
        this.formValidate.imageName = '';
      }
      if (this.formValidate.id) {
        const newObj = JSON.parse(JSON.stringify(this.formValidate));
        if (this.formValidate.dockerContent != '') {
          newObj.dockerContent = JSON.stringify(this.formValidate.dockerContent);
        }
        updateTarget(this.formValidate.id, newObj).then((res) => {
          if (res.code == 1) {
            this.targetModal.show = false;
            this.queryTargetList();
            this.$Message.info({
              content: '修改靶机成功',
              duration: 3
            });
          }
        });
      } else {
        const newObj = JSON.parse(JSON.stringify(this.formValidate));
        if (this.formValidate.dockerContent != '') {
          newObj.dockerContent = JSON.stringify(this.formValidate.dockerContent);
        }
        createTarget(newObj).then((data) => {
          this.cancelLoading('targetModal');
          if (data.code == 1) {
            this.$Message.info('靶标创建成功');
            this.targetModal.show = false;
            //this.queryTargetList();
            this.refreshIcon();
          } else {
            this.$Message.warning(data.message);
          }
        });
      }
    },
    saveTarget() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.createTarget();
        } else {
          this.cancelLoading('targetModal');
        }
      });
    },
    getTargetInfo(data) {
      this.targetModal.show = true;
      this.targetModal.title = '修改漏洞靶标';
      this.targetModal.add = false;
      this.uploaderror = false;
      this.showTip = false;
      this.filename = '';
      this.dockerFilename = '';
      this.curTarget = '';
      if (data) {
        this.curTarget = JSON.parse(JSON.stringify(data));
        this.formValidate = JSON.parse(JSON.stringify(data));
        if (data.dockerContent) {
          this.formValidate.dockerContent = JSON.parse(data.dockerContent);
          this.FormValidate.ImageSource = '2';
        } else this.FormValidate.ImageSource = '1';
        this.filename = JSON.parse(JSON.stringify(data)).docName;
        this.dockerFilename = this.formValidate.dockerContent.dockerName;
      } else {
        delete this.formValidate.id;
        this.targetModal.show = true;
        this.targetModal.add = true;
        this.targetModal.title = '创建漏洞靶标';
        this.cancel('formValidate');
      }
    },
    debounceSearch: debounce(function() {
      this.changePage(1);
    }, 500),
    changePage(page) {
      this.query.pageIndex = page;
      this.queryTargetList();
    },
    changeSize(size) {
      this.query.pageSize = size;
      this.queryTargetList();
    },
    refreshIcon() {
      this.query = {
        pageIndex: 1,
        pageSize: 10
      };
      this.queryTargetInfo = {};
      this.setStyle();
      this.creatByMeModal = false;
      this.queryTargetInfo.visibility = '';
      this.queryTargetList();
    },
    cancelLoading(name) {
      this[name].loading = false;
      setTimeout(() => {
        this[name].loading = true;
      });
    },
    cancel(name) {
      this.$refs[name].resetFields();
      //this.dealDelFileData();
      this.formValidate = {
        creator: this.USER_ID,
        cve: '', //CVE编号
        description: '', //漏洞描述
        imageId: '',
        imageName: '', //镜像名称
        visibility: 'share', //可见范围
        leakType: '', //漏洞名称
        leakLevel: '', //漏洞等级
        openPort: '', //开放端口
        name: '', //名称
        targetlibrary: '', //靶标知识库
        docName: '', //说明文档
        docPath: '', //说明文档
        explainFileRecordId: '', //说明文档

        dockerContent: { tempId: '', dockerName: '', dockerPath: '', flagPath: '', cmd: '' }
      };
      this.FormValidate = {
        ImageSource: '1' //镜像来源 '1'为选择已有镜像，'2'为上传docker
      };
    },
    dealDelFileData() {
      if (
        this.formValidate.explainFileRecordId &&
        (!this.curTarget ||
          this.curTarget.explainFileRecordId != this.formValidate.explainFileRecordId)
      ) {
        this.delFile(this.formValidate.explainFileRecordId);
      }
    },
    getAllImage() {
      let obj = {};
      let search = {
        pageIndex: 1,
        pageSize: 99999
      };
      getallImage(obj, search).then((data) => {
        if (data.code === 1) {
          this.imageList = data.data.items.filter(
            (item) => item.access === true && item.status === 'active'
          );
        } else {
          this.$Message.warning(data.message);
        }
      });
      getAllDocker(search).then((res) => {
        if (res.code === 1) {
          this.dockerList = res.data.items;
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    changeImage(image) {
      if (image) {
        this.formValidate.imageName = image.label;
        this.formValidate.imageId = image.value;
      }
    },
    handleFormatError() {
      this.showTip = true;
      this.uploadList = [];
    },
    handleBeforeUpload(file) {
      this.uploadList = this.$refs.upload.fileList;
      return true;
    },
    handleBeforeUploadDocker(file) {
      this.uploadDockerList = this.$refs.uploadDocker.fileList;
      this.speed = 0;
      return true;
    },
    handleUploadSize() {
      this.showTip = true;
      this.uploadList = [];
    },
    getImageUrl(res) {
      if (res.code == 1) {
        let file = res;
        let src = file.data;
        this.uploaderror = false;
        this.showTip = false;
        this.filename = file.info.originalName;
        this.formValidate.docName = file.info.originalName;
        this.formValidate.docPath = src;
        this.formValidate.explainFileRecordId = file.info.id;
        //    	this.iconSrc = `http://172.18.100.1/Learn${src}`;
      } else {
        this.$Message.warning(res.message);
      }
      this.uploadList = [];
    },
    getDockerUrl(res) {
      if (res.code === 1) {
        this.formValidate.dockerContent.dockerName = res.info.originalName;
        this.formValidate.dockerContent.dockerPath = res.data;
        this.dockerFilename = res.info.originalName;
      }

      this.uploadDockerList = [];
    },
    clearDoc() {
      //				this.delFile(this.formValidate.explainFileRecordId);
      this.filename = '';
      this.formValidate.docName = '';
      this.formValidate.docPath = '';
      this.formValidate.explainFileRecordId = '';
    },
    clearDocker() {
      this.dockerFilename = '';
      this.formValidate.dockerContent.dockerName = '';
      this.formValidate.dockerContent.dockerPath = '';
    },
    //用于删除之前上传的现在没有使用的文件
    delFile(id) {
      delfile(id)
        .then((data) => {
          this.delDocIds = [];
          if (data.code == 1) {
            //							this.$Message.info(data.message);
          } else {
            //							this.$Message.warning(data.message);
          }
        })
        .catch((error) => {
          this.delDocIds = [];
        });
    },
    // 按钮点击状态
    setReBtnStatus(params) {
      let userid = params.creator;
      if (userid === this.USER_ID || this.isRootDesigner) {
        return false;
      } else {
        return true;
      }
    },
    // 计算index
    handleProIndex(key) {
      return (this.query.pageIndex - 1) * this.query.pageSize + key + 1;
    },
    // 鼠标移入移出
    enterDelIcon(key) {
      this.targetList[key].delIcon = require('../../assets/project/delNote-h.png');
    },
    leaveDelIcon(key) {
      this.targetList[key].delIcon = require('../../assets/project/delNote-d.png');
    },
    enterModifyIcon(key) {
      this.targetList[key].modifyIcon = require('../../assets/project/modifys-h.png');
    },
    leaveModifyIcon(key) {
      this.targetList[key].modifyIcon = require('../../assets/project/modifys.png');
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 1 || val === 'share') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 0 || val === 'private') {
        text = '个人';
        color = '#FFA500';
      } else if (val === 2 || val === 'public') {
        text = '系统';
        color = '#4169E1';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    filterLevel(level) {
      if (level == 'low') {
        return '低危';
      } else if (level == 'middle') {
        return '中危';
      } else if (level == 'high') {
        return '高危';
      }
    },
    handleDownIcon(val) {
      if (val) {
        return require('../../assets/project/download-h.png');
      } else {
        return require('../../assets/project/download-s.png');
      }
    },
    // 设置知否可点击
    setIsClick(item) {
      if (
        item.visibility === 'public' ||
        item.visibility === 2 ||
        (item.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        return true;
      }
    },
    setImgSrc(item) {
      if (
        item.visibility === 'public' ||
        item.visibility === 2 ||
        (item.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if (
        item.visibility === 'public' ||
        item.visibility === 2 ||
        (item.creator !== this.USER_ID && !this.isRootDesigner)
      ) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    getProgress(progressEvent) {
      var aaspeed = Number(progressEvent.loaded - this.loaded) || 0;
      this.loaded = progressEvent.loaded;
      if (aaspeed > 1024 * 1024) {
        this.speed = (Math.round((aaspeed * 100) / (1024 * 1024)) / 100).toString() + 'MB/s';
      } else {
        this.speed = (Math.round((aaspeed * 100) / 1024) / 100).toString() + 'KB/s';
      }
    },
    getFileSize(size) {
      let fileSize;
      if (size > 1024 * 1024) {
        fileSize = (Math.round((size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
      } else {
        fileSize = (Math.round((size * 100) / 1024) / 100).toString() + 'KB';
      }
      return fileSize;
    },
    changePublic(val) {
      if (val == 'share' && this.targetModal.add) {
        this.formValidate.imageId = '';
      }
    },

    openCheck(item) {
      item.subFlag = false;
      this.$refs.check.openCheck(item);
    },
    addImage() {
      this.$refs.check.addImage();
    },
    setColor(item) {
      let color = 'grey';
      switch (item.status) {
        case 'error': // 创建失败
          color = '#ff4242';
          return color;
          break;
        case 'create_ing': // 镜像生成中
          color = '#ff8244';
          return color;
          break;
        case 'saving': // 创建中
          color = '#ff8244';
          return color;
          break;
        case 'active': // 创建成功
          color = '#06b649';
          return color;
          break;
      }
    },
    setScriptColor(item) {
      let color = 'grey';
      switch (item.verify) {
        case 'none': // 未验证
          color = 'grey';
          return color;
          break;
        case 'verify_ing': // 验证中
          color = '#ff8244';
          return color;
          break;
        case 'active': // 验证成功
          color = '#06b649';
          return color;
          break;
        case 'error': // 验证失败
          color = '#ff4242';
          return color;
          break;
      }
    },
    // 修改靶标的时候，如果为选择已有镜像，上传docker为空串，切换时收集信息报错，置为对象格式
    setImageSource() {
      if (this.formValidate.id) {
        this.formValidate.dockerContent = {
          tempId: '',
          dockerName: '',
          dockerPath: '',
          flagPath: '',
          cmd: ''
        };
        this.dockerFilename = '';
      }
    },

    mouseOver(item) {
      if (item.verify == 'error' || item.verify == 'active') {
        let query = {
          type: 'verify_target'
        };
        getOperateInfo(item.id, query)
          .then((res) => {
            if (res.code == 1) {
              let msg = res.data.msg;
              this.$set(item, 'msg', msg);
            } else {
              this.$Message.error({ content: '获取原因失败', duration: 3 });
            }
          })
          .catch((err) => {
            this.$message.error({ content: err.message, duration: 3 });
          });
      }
    }
  },
  mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
    this.queryTargetList();
    this.getAllImage();
    this.queryAllRange();
  },
  watch: {},
  beforeDestroy() {
    clearTimeout(this.proSetInterval);
  }
};
</script>
<style scoped>
/* 新样式 */
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
#quesDetail {
  display: table;
  width: 100%;
  border: 1px solid var(--table-border);
  table-layout: fixed;
  word-break: break-all;
}

#quesDetail p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}

#quesDetail p span {
  display: table-cell;
  border-bottom: 1px solid var(--table-border);
}
.chose-wrap {
  display: flex;
  justify-content: space-between;
  padding: 3px 8px;
  background-color: var(--table-tr-hover-color);
  align-items: center;
  margin-top: 10px;
}

.chose-name {
  width: 300px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chose-s-icon {
  width: 15px;
  height: 17px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}

.chose-s2-icon {
  width: 13px;
  height: 15px;
  display: inline-block;
  margin-bottom: 1px;
  margin-right: 10px;
}
.SelForm {
  position: relative;
}
.AddImageBtn {
  position: absolute;
  right: 20px;
  top: 5px;
}
.btn1 {
  font-size: 26px;
  color: #1563C2 ;
  margin-bottom: 5px;
}
.btn2 {
  font-size: 26px;
  color: #b1451b;
  margin-bottom: 5px;
}
.ios-alert1 {
  position: absolute;
  top: 0px;
  right: -24px;
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
</style>
